﻿using System;
using System.Collections.Generic;
using System.Text;

using ET;
using Marx;

namespace Server
{
    [ObjectSystem]
    public class AppPingAwakeSystem : AwakeSystem<AppPingComponent>
    {
        public override void Awake(AppPingComponent self)
        {
            self.Awake();
        }
    }

    public class AppPingComponent : Entity, IAppStartup, IAwake
    {
        public static AppPingComponent Instance { get; private set; }

        public void Awake()
        {
            Instance = this;
            Host.Instance.AddStarter(this);
        }

        public async ETTask Startup()
        {
            int currentProcess = StartConfig.Instance.CurrentProcess.ID;
            var processes = StartConfig.Instance.Processes;
            foreach (var process in processes)
            {
                if(currentProcess == process.ID)
                {
                    continue;
                }

                await PingUntilSuccess(process.ID);
            }
        }

        public async ETTask<bool> Ping(int processId)
        {
            try
            {
                var session = NetInnerComponent.Instance.Get(processId);
                var response = await session.Call(new SSPingRequest());
                if (response.Error != ResultCode.Success)
                {
                    return false;
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async ETTask PingUntilSuccess(int process)
        {
            while (true)
            {
                var result = await Ping(process);
                if (result)
                {
                    break;
                }

                Log.Info($"Ping server process:{process} failed, try again after 0.5 second");
                if(!await TimerComponent.Instance.WaitAsync(500))
                {
                    throw new Exception("Ping fail, unknown error");
                }
            }
        }
    }
}
